﻿using DiLe.Mes.Model.Cloud.Statistics;
using DiLe.Mes.Model.Local.Entity;
using EasyNetQ;
using MapleLeaf.Core.EventBus;
using Quartz;

namespace DiLe.Mes.Local.Jobs {
    /// <summary>
    /// 
    /// </summary>
    [DisallowConcurrentExecution]
    public class PointStatisticsJob : IJob {
        private readonly static IBus _ibus = AppHelper.GetService<IBus>();
        private readonly static string AppId = AppHelper.AppSettingInfo?.AppId ?? "0";

        /// <summary>
        /// 
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public async Task Execute(IJobExecutionContext context) {
            await PushEMPointStatisticsAsync();
            await PushFMPointStatisticsAsync();
            await PushAOIPointStatisticsAsync();
            await PushFormingPointStatisticsAsync();
            await PushOtherPointStatisticsAsync();
            await PushTrimPointStatisticsAsync();
        }
        /// <summary>
        /// 电能表
        /// </summary>
        private async Task PushEMPointStatisticsAsync() {
            var currentdate = DateTime.Now.Date.AddDays(-1);

            var datalist = await PointStatisticsHelper.GetEMPointStatisticsListAsync(currentdate);
            if (datalist.None()) {
                return;
            }
            var dateStr = currentdate.ToString("yyyy-MM-dd");
            List<string> NameArr = [];
            var pushDatas = new List<EMPointStatisticsEntity>();
            foreach (var data in datalist) {
                int orderNum = 0;
                if (data.DeviceNo.Equals("电能表-1", StringComparison.CurrentCultureIgnoreCase)) {
                    NameArr = PointStatisticsHelper.NameArr1;
                    orderNum = 1;
                } else if (data.DeviceNo.Equals("电能表-2", StringComparison.CurrentCultureIgnoreCase)) {
                    NameArr = PointStatisticsHelper.NameArr2;
                    orderNum = 40;
                } else if (data.DeviceNo.Equals("电能表-6", StringComparison.CurrentCultureIgnoreCase)) {
                    NameArr = PointStatisticsHelper.NameArr6;
                    orderNum = 60;
                }
                var valueArr = data!.EcTotal.Split(",");
                if (valueArr.Length < NameArr.Count) {
                    continue;
                }
                for (int i = 0; i < NameArr.Count; i++) {
                    var name = NameArr[i];
                    var value = valueArr[i];

                    var m = new EMPointStatisticsEntity {
                        ElectricEnergy = value,
                        Name = name,
                        OrderNumber = ++orderNum,
                        Date = dateStr,
                        FactoryId = AppId.ToLong(),
                        Type = "电能表",
                    };
                    pushDatas.Add(m);
                }
            }
            var model = new MessageModel() {
                SendMsg = pushDatas.ToJosn(),
                MsgSign = "EMPointStatistics"
            };
            _ibus.SendReceive.Send("data_push_statistics", model);
        }


        /// <summary>
        /// 流量表
        /// </summary>
        public async Task PushFMPointStatisticsAsync() {
            var currentdate = DateTime.Now.Date.AddDays(-1);
            var dataList = await PointStatisticsHelper.GetFMPointStatisticsListAsync(currentdate);
            if (dataList.None()) {
                return;
            }
            var dateStr = currentdate.ToString("yyyy-MM-dd");
            var pushDatas = new List<FMPointStatisticsEntity>();
            foreach (var data in dataList) {
                List<(int num, string name)> NameArr = [];
                if (data.DeviceNo.Equals("流量计-3", StringComparison.CurrentCultureIgnoreCase)) {
                    NameArr = PointStatisticsHelper.FMNameArr3;
                } else if (data.DeviceNo.Equals("流量计-5", StringComparison.CurrentCultureIgnoreCase)) {
                    NameArr = PointStatisticsHelper.FMNameArr5;
                } else if (data.DeviceNo.Equals("流量计-2", StringComparison.CurrentCultureIgnoreCase)) {
                    NameArr = PointStatisticsHelper.FMNameArr2;
                }
                var valueArr = data!.FlowTotal.Split(",");
                if (valueArr.Length < NameArr.Count) {
                    continue;
                }
                for (int i = 0; i < NameArr.Count; i++) {
                    var (num, name) = NameArr[i];
                    var value = valueArr[i];

                    var m = new FMPointStatisticsEntity {
                        FlowRate = value,
                        Name = name,
                        OrderNumber = num,
                        Date = dateStr,
                        FactoryId = AppId.ToLong(),
                        Type = "流量表",
                    };
                    pushDatas.Add(m);
                }
            }
            var model = new MessageModel() {
                SendMsg = pushDatas.ToJosn(),
                MsgSign = "FMPointStatistics"
            };
            _ibus.SendReceive.Send("data_push_statistics", model);

        }

        /// <summary>
        /// AOI
        /// </summary>
        public async Task PushAOIPointStatisticsAsync() {
            var currentdate = DateTime.Now.Date.AddDays(-1);
            var dataList = await PointStatisticsHelper.GetAOIPointStatisticsListAsync(currentdate);
            if (dataList.None()) {
                return;
            }
            var dateStr = currentdate.ToString("yyyy-MM-dd");
            var pushDatas = new List<AOIPointStatisticsEntity>();
            foreach (var data in dataList) {
                var m = data.Adapt<AOIPointStatisticsEntity>();
                m.AcquisitionTime = dateStr;
                m.FactoryId = AppId.ToLong();
                pushDatas.Add(m);
            }
            var model = new MessageModel() {
                SendMsg = pushDatas.ToJosn(),
                MsgSign = "AOIPointStatistics"
            };
            _ibus.SendReceive.Send("data_push_statistics", model);

        }
        /// <summary>
        /// Trim
        /// </summary>
        public async Task PushTrimPointStatisticsAsync() {
            var currentdate = DateTime.Now.Date.AddDays(-1);
            var dataList = await PointStatisticsHelper.GetTrimPointStatisticsListAsync(currentdate);
            if (dataList.None()) {
                return;
            }
            var dateStr = currentdate.ToString("yyyy-MM-dd");
            var pushDatas = new List<TrimPointStatisticsEntity>();
            foreach (var data in dataList) {
                var m = data.Adapt<TrimPointStatisticsEntity>();
                m.AcquisitionTime = dateStr;
                m.FactoryId = AppId.ToLong();
                pushDatas.Add(m);
            }
            var model = new MessageModel() {
                SendMsg = pushDatas.ToJosn(),
                MsgSign = "TrimPointStatistics"
            };
            _ibus.SendReceive.Send("data_push_statistics", model);

        }
        /// <summary>
        /// forming
        /// </summary>
        public async Task PushFormingPointStatisticsAsync() {
            var currentdate = DateTime.Now.Date.AddDays(-1);
            var dataList = await PointStatisticsHelper.GetFormingPointStatisticsListAsync(currentdate);
            if (dataList.None()) {
                return;
            }
            var dateStr = currentdate.ToString("yyyy-MM-dd");
            var pushDatas = new List<FormingPointStatisticsEntity>();
            foreach (var data in dataList) {
                var m = data.Adapt<FormingPointStatisticsEntity>();
                m.AcquisitionTime = dateStr;
                m.FactoryId = AppId.ToLong();
                pushDatas.Add(m);
            }
            var model = new MessageModel() {
                SendMsg = pushDatas.ToJosn(),
                MsgSign = "FormingPointStatistics"
            };
            _ibus.SendReceive.Send("data_push_statistics", model);

        }
        /// <summary>
        /// 1311
        /// </summary>
        public async Task PushOtherPointStatisticsAsync() {
            var currentdate = DateTime.Now.Date.AddDays(-1);
            var dataList = await PointStatisticsHelper.GetOtherPointStatisticsListAsync(currentdate);
            if (dataList.None()) {
                return;
            }
            var dateStr = currentdate.ToString("yyyy-MM-dd");
            var pushDatas = new List<OtherPointStatisticsEntity>();
            foreach (var data in dataList) {
                var m = data.Adapt<OtherPointStatisticsEntity>();
                m.AcquisitionTime = dateStr;
                m.FactoryId = AppId.ToLong();
                pushDatas.Add(m);
            }
            var model = new MessageModel() {
                SendMsg = pushDatas.ToJosn(),
                MsgSign = "OtherPointStatistics"
            };
            _ibus.SendReceive.Send("data_push_statistics", model);

        }
    }
    /// <summary>
    /// 
    /// </summary>
    public static class PointStatisticsHelper {

        public static readonly List<(int num, string name)> FMNameArr3 = [(2, "AB线打浆供水-流量表2"), (3, "CD线打浆供水-流量表3"), (4, "AB线回收-流量表4"), (5, "AB线回收-流量表5")];
        public static readonly List<(int num, string name)> FMNameArr2 = [(1, "总供水-流量表1")];
        public static readonly List<(int num, string name)> FMNameArr5 = [(6, "CD线回收-流量表6"), (7, "CD线回收-流量表7")];

        public static readonly List<string> NameArr1 = ["AB线真空泵1#", "1311-01", "A线制浆1#", "AB线空压1#", "B线制浆2#", "AB线真空泵2#", "AB线空压2#", "B线制浆1#", "老配电房总电1#"];
        public static readonly List<string> NameArr2 = ["CD线空压2#", "A线制浆2#", "老配电房总电2#", "AB线真空3#", "B线制浆3#"];
        public static readonly List<string> NameArr6 = ["C线制浆1#", "三合一真空", "CD线真空1#", "CD线真空2#", "CD线真空3#", "新配电室总电1#", "新配电室总电2#", "圣代杯空压机", "三合一空压机", "D线制浆5#", "D线制浆4#", "D线制浆3#", "D线制浆2#", "D线制浆1#", "C线制浆5#", "C线制浆4#", "C线制浆3#", "C线制浆2#"];


        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public static async Task<List<EMPointInfoEntity>> GetEMPointStatisticsListAsync(DateTime currentdate) {
            DateTime startDate = currentdate.AddDays(-1).AddHours(8);
            DateTime endDate = currentdate.AddHours(8);
            var wxp = Expressionable.Create<EMPointInfoEntity>();
            wxp.And(x => x.CreateTime >= startDate);
            wxp.And(x => x.CreateTime <= endDate);

            var datalist = await SqlSugarHelper.LocalDb.Queryable<EMPointInfoEntity>()
                                                   .Where(wxp.ToExpression())
                                                   .GroupBy(it => it.DeviceNo)
                                                   .Select(it => new { it.DeviceNo, Id = SqlFunc.AggregateMax(it.Id) })
                                                   .MergeTable()
                                                   .LeftJoin<EMPointInfoEntity>((a, b) => a.Id == b.Id)
                                                   .Select((a, b) => b)
                                                   .ToListAsync();
            return datalist;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public static async Task<List<FMPointInfoEntity>> GetFMPointStatisticsListAsync(DateTime currentdate) {
            DateTime startDate = currentdate.AddDays(-1).AddHours(8);
            DateTime endDate = currentdate.AddHours(8);
            var wxp = Expressionable.Create<FMPointInfoEntity>();
            wxp.And(x => x.CreateTime >= startDate);
            wxp.And(x => x.CreateTime <= endDate);

            var datalist = await SqlSugarHelper.LocalDb.Queryable<FMPointInfoEntity>()
                                                   .Where(wxp.ToExpression())
                                                   .GroupBy(it => it.DeviceNo)
                                                   .Select(it => new { it.DeviceNo, Id = SqlFunc.AggregateMax(it.Id) })
                                                   .MergeTable()
                                                   .LeftJoin<FMPointInfoEntity>((a, b) => a.Id == b.Id)
                                                   .Select((a, b) => b)
                                                   .ToListAsync();
            return datalist;
        }

        /// <summary>
        /// AOI
        /// </summary>
        /// <returns></returns>
        public static async Task<List<AOIPointInfoEntity>> GetAOIPointStatisticsListAsync(DateTime currentdate) {
            DateTime startDate = currentdate.AddDays(-1).AddHours(8);
            DateTime endDate = currentdate.AddHours(8);
            var wxp = Expressionable.Create<AOIPointInfoEntity>();
            wxp.And(x => x.CreateTime >= startDate);
            wxp.And(x => x.CreateTime <= endDate);

            var datalist = await SqlSugarHelper.LocalDb.Queryable<AOIPointInfoEntity>()
                                                   .Where(wxp.ToExpression())
                                                   .GroupBy(it => it.DeviceNo)
                                                   .Select(it => new { it.DeviceNo, Id = SqlFunc.AggregateMax(it.Id) })
                                                   .MergeTable()
                                                   .LeftJoin<AOIPointInfoEntity>((a, b) => a.Id == b.Id)
                                                   .Select((a, b) => b)
                                                   .ToListAsync();
            return datalist;
        }

        /// <summary>
        /// TRIM
        /// </summary>
        /// <returns></returns>
        public static async Task<List<TrimPointInfoEntity>> GetTrimPointStatisticsListAsync(DateTime currentdate) {
            DateTime startDate = currentdate.AddDays(-1).AddHours(8);
            DateTime endDate = currentdate.AddHours(8);
            var wxp = Expressionable.Create<TrimPointInfoEntity>();
            wxp.And(x => x.CreateTime >= startDate);
            wxp.And(x => x.CreateTime <= endDate);

            var datalist = await SqlSugarHelper.LocalDb.Queryable<TrimPointInfoEntity>()
                                                   .Where(wxp.ToExpression())
                                                   .GroupBy(it => it.DeviceNo)
                                                   .Select(it => new { it.DeviceNo, Id = SqlFunc.AggregateMax(it.Id) })
                                                   .MergeTable()
                                                   .LeftJoin<TrimPointInfoEntity>((a, b) => a.Id == b.Id)
                                                   .Select((a, b) => b)
                                                   .ToListAsync();
            return datalist;
        }
        /// <summary>
        /// 成型
        /// </summary>
        /// <returns></returns>
        public static async Task<List<PointInfoEntity>> GetFormingPointStatisticsListAsync(DateTime currentdate) {
            DateTime startDate = currentdate.AddDays(-1).AddHours(8);
            DateTime endDate = currentdate.AddHours(8);
            var wxp = Expressionable.Create<PointInfoEntity>();
            wxp.And(x => x.CreateTime >= startDate);
            wxp.And(x => x.CreateTime <= endDate);

            var datalist = await SqlSugarHelper.LocalDb.Queryable<PointInfoEntity>()
                                                   .Where(wxp.ToExpression())
                                                   .GroupBy(it => it.DeviceNo)
                                                   .Select(it => new { it.DeviceNo, Id = SqlFunc.AggregateMax(it.Id) })
                                                   .MergeTable()
                                                   .LeftJoin<PointInfoEntity>((a, b) => a.Id == b.Id)
                                                   .Select((a, b) => b)
                                                   .ToListAsync();
            return datalist;
        }
        /// <summary>
        /// 1311
        /// </summary>
        /// <returns></returns>
        public static async Task<List<OtherPointInfoEntity>> GetOtherPointStatisticsListAsync(DateTime currentdate) {
            DateTime startDate = currentdate.AddDays(-1).AddHours(8);
            DateTime endDate = currentdate.AddHours(8);
            var wxp = Expressionable.Create<OtherPointInfoEntity>();
            wxp.And(x => x.CreateTime >= startDate);
            wxp.And(x => x.CreateTime <= endDate);

            var datalist = await SqlSugarHelper.LocalDb.Queryable<OtherPointInfoEntity>()
                                                   .Where(wxp.ToExpression())
                                                   .GroupBy(it => it.DeviceNo)
                                                   .Select(it => new { it.DeviceNo, Id = SqlFunc.AggregateMax(it.Id) })
                                                   .MergeTable()
                                                   .LeftJoin<OtherPointInfoEntity>((a, b) => a.Id == b.Id)
                                                   .Select((a, b) => b)
                                                   .ToListAsync();
            return datalist;
        }
    }
}
